<!-- 积分类型弹窗 -->
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { IDbFormItem } from '@/types/global'
import DuiForm from '@/common-ui/dui-form/index.vue'
import * as scoreApi from '@/api/score'
import useNotic from '@/hooks/useNotic'
import type { IScoreType } from '../config/type'

const emits = defineEmits(['refresh'])

defineProps({
  // 标题
  title: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})
// 详情id
const infoId = ref('')
// 弹窗表单数据
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const formConfig = reactive<IDbFormItem[]>([
  { label: '积分类型', prop: 'typeName', type: 'input', required: true, span: 24 },
  { label: '积分编码', prop: 'typeCode', type: 'input', span: 24 }
])
// 表单默认数据
const defaultData: IScoreType = {
  typeName: '',
  typeCode: ''
}
// 表单数据
const formData = ref<IScoreType>(JSON.parse(JSON.stringify(defaultData)))
// 是否显示弹窗
const showDialog = ref(false)

/**
 * 打开弹窗并初始化数据
 */
function init(data?: any) {
  infoId.value = data?.id ?? ''
  const resData: any = data || {}
  const defaultForm = JSON.parse(JSON.stringify(defaultData as any))
  Object.keys(defaultForm).forEach((key) => {
    ;(formData.value as any)[key] = resData[key] ?? defaultForm[key]
  })
  showDialog.value = true
}

/**
 * 点击提交
 */
function submitClick() {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      let reqFunc = scoreApi.addScoreType
      let params: any = formData.value
      if (infoId.value) {
        reqFunc = scoreApi.editScoreType
        params = { ...formData.value, id: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled" />
    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
